package com.todod.common.util;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * spring el 解析
 * 
 * @ClassName: SpringElUtil
 * @Description:
 * @author gsh
 * @date 2020年7月27日
 *
 */
public class SpringElUtil {
	static Logger log = LoggerFactory.getLogger(SpringElUtil.class);

	/**
	 * 注入多个变量
	 *
	 * @param expr #{#shopId}.#{#typeId}.#{#paging.page}
	 * @param map
	 * @return
	 */
	public static Object readExpr(String expr, Map<String, Object> map) {

		try {
			ExpressionParser parser = new SpelExpressionParser();
			Expression expression = parser.parseExpression(expr, new TemplateParserContext());

			EvaluationContext context = new StandardEvaluationContext();

			for (Map.Entry<String, Object> entry : map.entrySet()) {
				context.setVariable(entry.getKey(), entry.getValue());
			}

			return expression.getValue(context, Object.class);
		} catch (Exception e) {
			log.error("error-info", e);

			return true;
		}
	}

	public static void main(String[] args) {
		String template = "你好";

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("num", 155);
		map.put("num1", 155);
		map.put("num2", 155);
		map.put("aaaa", "hahahahaha");

		Object str = readExpr(template, map);

		System.out.println(str);

	}

}
